package com.android.loveandhate.detector.image;

import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.FaceDetector;
import android.util.Log;
import android.view.View;

public class FaceDetect extends View {
	private static final boolean DEBUG = true;
	private static final int NUM_FACES = 64; // max is 64
	
	private BitmapFactory.Options bfo = new BitmapFactory.Options();
	private Bitmap sourceImage;
	private int imageWidth, imageHeight;
	
	private FaceDetector arrayFaces;
    private FaceDetector.Face getAllFaces[] = new FaceDetector.Face[NUM_FACES];
    private FaceDetector.Face face = null;
    
    private List <Face> faces = new LinkedList<Face>();
	
	public FaceDetect( Context context ) {
		super(context);
        bfo.inPreferredConfig = Bitmap.Config.RGB_565;
	}
	
	public void findFaces( int img ) {
		loadImage( img );
		localizeAllFaces();
		validateFaces();
	}
	
	private void loadImage( int img ) {
		sourceImage = BitmapFactory.decodeResource( getResources(), img, bfo);
		defineImageSize();
	}
	
	private void defineImageSize() {
		imageWidth = sourceImage.getWidth();
        imageHeight = sourceImage.getHeight();
	}
	
	private void localizeAllFaces() {
		arrayFaces = new FaceDetector( imageWidth, imageHeight, NUM_FACES );
		arrayFaces.findFaces(sourceImage, getAllFaces);
	}
	
	private void validateFaces() {
		for (int i = 0; i < getAllFaces.length; i++) {
            face = getAllFaces[i];
            try {
            	Face faceData = new Face( face, DEBUG );
            	faces.add( faceData );
            }
            catch (Exception e) {
         	   if (DEBUG) Log.e("Face", i + " is null");
            }
       }
	}
	
	public int getImageWidth() { return imageWidth; }
	public int getImageHeight() { return imageHeight; }
	public Bitmap getSourceImage() { return sourceImage; }
	public List <Face> getFaces() { return faces; }
}
